<template>
  <view class="container">
    <!-- 头部返回 -->
    <view class="header">
      <uni-icons type="arrowleft" size="24" @click="goBack"></uni-icons>
      <!-- <text class="title">个人信息</text> -->
    </view>

    <!-- 个人信息表单 -->
    <view class="form-container">
      <!-- 头像 -->
      <view class="form-item avatar-item">
        <text class="label">头像</text>
        <view class="avatar-wrapper" @click="showAvatarActionSheet">
          <image :src="userInfoda.avatar || defaultAvatar" mode="aspectFill" class="avatar"></image>
          <uni-icons type="arrowright" size="16" color="#999"></uni-icons>
        </view>
      </view>

      <!-- 用户名 -->
      <view class="form-item">
        <text class="label">用户名</text>
        <input v-model="userInfoda.username" placeholder="请输入用户名" class="input" />
      </view>

      <!-- 邮箱 -->
      <view class="form-item">
        <text class="label">邮箱</text>
        <input v-model="userInfoda.email" placeholder="请输入邮箱" class="input" type="email" />
      </view>

      <!-- 手机号 -->
      <view class="form-item">
        <text class="label">手机号</text>
        <input v-model="userInfoda.phone" placeholder="请输入手机号" class="input" type="tel" />
      </view>

      <!-- 性别 -->
      <view class="form-item">
        <text class="label">性别</text>
        <picker mode="selector" :range="genderOptions" @change="onGenderChange">
          <view class="picker">
            {{ userInfoda.gender || '请选择性别' }}
            <uni-icons type="arrowright" size="16" color="#999"></uni-icons>
          </view>
        </picker>
      </view>

      <!-- 地区 -->
      <view class="form-item">
        <text class="label">地区</text>
        <picker mode="region" @change="onRegionChange">
          <view class="picker">
            {{ userInfoda.region || '请选择地区' }}
            <uni-icons type="arrowright" size="16" color="#999"></uni-icons>
          </view>
        </picker>
      </view>
    </view>

    <!-- 保存按钮 -->
    <button class="save-btn" @click="saveInfo">
      保存修改
    </button>
    <button class="save-btn" @click="handleLogout">
      退出登录
      <uni-icons type="arrowright" size="16" color="#999"></uni-icons>
    </button>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { useUserStore } from '@/stores/userdata';

const API_BASE_URL = 'https://37ace603.r34.cpolar.top'
const userStore = useUserStore();
const defaultAvatar = 'https://img1.baidu.com/it/u=4142671647,1106015361&fm=253&fmt=auto&app=120&f=JPEG?w=800&h=800'

const userInfoda = ref({
  avatar: '',
  username: '',
  email: '',
  phone: '',
  gender: '',
  region: ''
});

const genderOptions = ['男', '女', '其他'];

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    // 先使用store中的基本信息
    userInfoda.value = {
      ...userInfoda.value,
      ...userStore.userData
    };

    // 获取完整的用户信息
    const res = await uni.request({
      url: `${API_BASE_URL}/account/wechat/userinfo/`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${userStore.userData.access_token}`
      }
    });
    console.log('222222',res.data)
    if (res.statusCode === 200 && res.data) {
      // 更新用户信息，保留原有值作为默认值
   
    } else {
      console.error('获取用户信息失败，响应:', res);
      throw new Error(res.data?.message || '获取用户信息失败');
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
    // 如果获取失败，至少显示store中的基本信息
    userInfoda.value = {
      ...userInfoda.value,
      ...userStore.userData
    };
    uni.showToast({
      title: '获取详细信息失败',
      icon: 'none'
    });
  }
};

// 初始化
onMounted(async () => {
  // 检查登录状态
  if (!userStore.userData?.access_token) {
    uni.showModal({
      title: '提示',
      content: '请先登录',
      showCancel: false,
      success: () => {
        uni.switchTab({
          url: '/views/my/index'
        });
      }
    });
    return;
  }
  
  await fetchUserInfo();
});

// 显示头像选择操作菜单
const showAvatarActionSheet = () => {
  let menuItems;

  // #ifdef MP-WEIXIN
  menuItems = ['使用微信头像', '从相册选择']
  // #endif

  // #ifdef H5
  menuItems = ['从相册选择']
  // #endif

  uni.showActionSheet({
    itemList: menuItems,
    success: (res) => {
      if (res.tapIndex === 0) {
        // #ifdef MP-WEIXIN
        if (menuItems[0] === '使用微信头像') {
          chooseWechatAvatar()
        } else {
          chooseImage()
        }
        // #endif

        // #ifdef H5
        chooseImage()
        // #endif
      } else if (res.tapIndex === 1) {
        chooseImage()
      }
    }
  })
}

// 选择微信头像
const chooseWechatAvatar = () => {
  // #ifdef MP-WEIXIN
  wx.chooseAvatar({
    success: async (res) => {
      const tempFilePath = res.tempFilePath
      await uploadAvatar(tempFilePath)
    },
    fail: (err) => {
      console.error('选择头像失败:', err)
      uni.showToast({
        title: '选择头像失败',
        icon: 'none'
      })
    }
  })
  // #endif
}

// 从相册选择图片
const chooseImage = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album'],
    success: async (res) => {
      const tempFilePath = res.tempFilePaths[0]
      await uploadAvatar(tempFilePath)
    },
    fail: (err) => {
      console.error('选择图片失败:', err)
      uni.showToast({
        title: '选择图片失败',
        icon: 'none'
      })
    }
  })
}

// 上传头像到服务器
const uploadAvatar = async (tempFilePath) => {
  try {
    uni.showLoading({
      title: '上传中...',
      mask: true
    })

    const uploadRes = await uni.uploadFile({
      url: `${API_BASE_URL}/upload/avatar/`,
      filePath: tempFilePath,
      name: 'avatar',
      header: {
        'Authorization': `Bearer ${userStore.userData.access_token}`
      }
    })

    if (uploadRes.statusCode === 200) {
      const data = JSON.parse(uploadRes.data)
      // 更新本地状态
      userInfoda.value.avatar = data.avatar_url
      // 更新store
      userStore.setUserInfo({
        ...userStore.userData,
        avatar: data.avatar_url
      })
      uni.showToast({
        title: '头像更新成功',
        icon: 'success'
      })
    } else {
      throw new Error('上传失败')
    }
  } catch (err) {
    console.error('上传头像失败:', err)
    uni.showToast({
      title: '上传失败，请重试',
      icon: 'none'
    })
  } finally {
    uni.hideLoading()
  }
}

// 性别选择
const onGenderChange = (e) => {
  userInfoda.value.gender = genderOptions[e.detail.value];
};

// 地区选择
const onRegionChange = (e) => {
  userInfoda.value.region = e.detail.value.join(' ');
};

// 保存用户信息
const saveInfo = async () => {
  try {
    uni.showLoading({
      title: '保存中...',
      mask: true
    });

    const res = await uni.request({
      url: `${API_BASE_URL}/account/wechat/userinfo/`,
      method: 'PUT',
      header: {
        'Authorization': `Bearer ${userStore.userData.access_token}`,
        'Content-Type': 'application/json'
      },
      data: {
        username: userInfoda.value.username,
        email: userInfoda.value.email,
        gender: userInfoda.value.gender,
        region: userInfoda.value.region
      }
    });

    if (res.statusCode === 200) {
      // 更新store
      userStore.setUserInfo({
        ...userStore.userData,
        ...userInfoda.value
      });

      uni.showToast({
        title: '保存成功',
        icon: 'success'
      });
    } else {
      throw new Error(res.data?.message || '保存失败');
    }
  } catch (error) {
    console.error('保存用户信息失败:', error);
    uni.showToast({
      title: error.message || '保存失败',
      icon: 'none'
    });
  } finally {
    uni.hideLoading();
  }
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 退出登录
const handleLogout = () => {
  uni.showModal({
    title: '提示',
    content: '确定要退出登录吗？',
    success: (res) => {
      if (res.confirm) {
        userStore.$reset();
        uni.showToast({
          title: '已退出登录',
          icon: 'success'
        });
        setTimeout(() => {
          uni.switchTab({
            url: '/views/index/index'
          });
        }, 1500);
      }
    }
  });
};
</script>

<style scoped>
.container {
  padding: 0;
  background:
    linear-gradient(135deg, #e6f0ff 0%, #d0e0ff 100%),
    repeating-linear-gradient(45deg,
      rgba(56, 182, 255, 0.03) 0px,
      rgba(56, 182, 255, 0.03) 2px,
      transparent 2px,
      transparent 4px);
  min-height: 100vh;
  color: #333;
}

/* 头部样式 */
.header {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(5px);
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  margin-left: 20rpx;
  color: #38b6ff;
}

/* 表单容器 */
.form-container {
  margin: 30rpx;
  background-color: rgba(255, 255, 255, 0.7);
  border-radius: 16rpx;
  backdrop-filter: blur(5px);
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

/* 表单项 */
.form-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 28rpx 32rpx;
  border-bottom: 1px solid rgba(56, 182, 255, 0.1);
}

.form-item:last-child {
  border-bottom: none;
}

.label {
  font-size: 32rpx;
  color: #333;
}

.input {
  flex: 1;
  text-align: right;
  font-size: 30rpx;
  color: #666;
  padding-right: 20rpx;
}

/* 头像项 */
.avatar-item {
  padding: 20rpx 32rpx;
}

.avatar-wrapper {
  display: flex;
  align-items: center;
}

.avatar {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  border: 2px solid rgba(56, 182, 255, 0.3);
  box-shadow: 0 0 10px rgba(56, 182, 255, 0.2);
}

/* 密码项 */
.password-wrapper {
  display: flex;
  align-items: center;
}

/* 选择器 */
.picker {
  display: flex;
  align-items: center;
  color: #666;
}

/* 保存按钮 */
.save-btn {
  margin: 40rpx 30rpx;
  background: linear-gradient(to right, #38b6ff, #00e5ff);
  color: white;
  border: none;
  border-radius: 40rpx;
  padding: 24rpx 0;
  font-size: 32rpx;
  box-shadow: 0 0 10px rgba(56, 182, 255, 0.2);
  transition: all 0.3s ease;
}

.save-btn:active {
  transform: scale(0.96);
  box-shadow: 0 0 5px rgba(56, 182, 255, 0.3);
}
</style>
